package io.wins.vertx.database;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

import javax.sql.DataSource;
import java.util.Properties;

public enum DataSourceFactory {
    INSTANCE;

    private final static Logger logger = LoggerFactory.getLogger(DataSource.class);
    private DataSource dataSource;

//    public DataSource getDataSource() {
//        if (dataSource == null) {
//            try {
//                final File configFile = new File("C:/Users/think/workspace/vertx/vertxLearn/src/main/resources/config.json");
//                init(JsonUtils.readFromFile(configFile));
//                DataSourceFactory.logger.info("Read config from file done");
//            } catch (final FileNotFoundException e) {
//                DataSourceFactory.logger.error("Failed to find config file:" + e);
//            }
//        }
//        return dataSource;
//    }

    public DataSource getDataSource() {
        return this.dataSource;
    }

    public void init(final JsonObject config) {
        if (config != null) {
            DataSourceFactory.logger.info("Initializing Datasource Factory");
            final JsonObject poolConfig = config.getJsonObject("pool");

            final Properties configProperties = new Properties();
            configProperties.putAll(poolConfig.getMap());

            this.dataSource = new HikariDataSource(new HikariConfig(configProperties));
            DataSourceFactory.logger.info("Initialize datasource done");
        }
    }
}
